//
//  DockTitleView.m
//  标签菜单
//
//  Created by Burn on 2019/7/23.
//  Copyright © 2019 menksoft. All rights reserved.
//

#import "DockTitleView.h"
#import "DockTitleStyle.h"
#import "TopRightPopover.h"
#import "UIColor+Color_Extension.h"

@interface DockTitleView ()
@property(strong,nonatomic) DockTitleStyle *style;
@property(strong,nonatomic) NSArray *titles;
@property(strong,nonatomic) UIScrollView *scrollView;
@property(strong,nonatomic) UILabel *bottomLine;
@property(strong,nonatomic) NSMutableArray *labels;
@property(assign,nonatomic) NSInteger currentIndex;


//  popover 按钮
@property(strong,nonatomic) UIButton *btn;
@end

@implementation DockTitleView

- (instancetype)initWith:(NSArray *)titles frame:(CGRect)frame style:(DockTitleStyle *)style{
    if (self = [super initWithFrame:frame]) {
        self.currentIndex = 0;
        self.style = style;
        self.titles = titles;
        [self createSuViews];
    }
    return self;
}

- (void)createSuViews{
    
    [self addSubview:self.scrollView];
    
    [self addLabels];
    
    [self setLabelFrames];
}


- (void)addLabels{
    for (int i = 0; i < self.titles.count; i++) {
        UILabel *label = [[UILabel alloc]init];
        label.tag = i;
        label.text = self.titles[i];
        label.textAlignment = NSTextAlignmentCenter;
        label.adjustsFontSizeToFitWidth = YES;
        label.textColor = i == 0 ? self.style.selectColor : self.style.normalColor;
        
        label.userInteractionEnabled = YES;
        UITapGestureRecognizer *labelTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(titleClick:)];
        [label addGestureRecognizer:labelTapGestureRecognizer];
        
        
        [self.labels addObject:label];
        [self.scrollView addSubview:label];
    }
    
    if (self.style.popover) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:[UIImage imageNamed:@"icons8-hemp_leaf_filled"] forState:UIControlStateNormal];
        button.frame = CGRectMake(self.bounds.size.width - 40, 0, 40, self.bounds.size.height);
        [self addSubview:button];
        [button addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
        self.btn = button;
    }
}

- (void)btnClick{
    
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    TopRightPopover *popover = [[TopRightPopover alloc]initWithFrame:CGRectZero];
    CGRect frameP = [self.btn convertRect:self.btn.frame toView:window];
    popover.frame = CGRectMake(self.bounds.size.width - 150, frameP.origin.y + self.bounds.size.height, 140, 200);
    UIView *shadow = [[UIView alloc]initWithFrame:window.bounds];
    shadow.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:.5];
    [window addSubview:shadow];
    [window addSubview:popover];
    [popover animation];
    
}

- (void)titleClick:(UIGestureRecognizer *)ges{
    
    UILabel *label = (UILabel *)ges.view;
    
    if (label.tag == self.currentIndex) {return;}
    
    UILabel *oldLabel = self.labels[self.currentIndex];
    label.textColor = self.style.selectColor;
    oldLabel.textColor = self.style.normalColor;
    
    self.currentIndex = label.tag;
    
    if (self.style.isNeedScale) {
        oldLabel.transform = CGAffineTransformIdentity;
        [UIView animateWithDuration:0.25 animations:^{
            label.transform = CGAffineTransformMakeScale(self.style.scaleRaange, self.style.scaleRaange);
        }];
    }
    
    if (self.style.isShowScrollLine) {
        [UIView animateWithDuration:.25 animations:^{
            self.bottomLine.frame = CGRectMake(CGRectGetMinX(label.frame), self.bottomLine.frame.origin.y, label.frame.size.width, self.bottomLine.frame.size.height);
        }];
    }
    
    if (self.style.isScrollEnanble) {
        [self moveToMiddle];
    }
    
    if ([self.delegate respondsToSelector:@selector(dockTitleClickWith:currentIndex:)]) {
        [self.delegate dockTitleClickWith:oldLabel.tag currentIndex:label.tag];
    }
}

- (void)moveToMiddle{
    UILabel *currentL = self.labels[self.currentIndex];
    CGFloat offset = currentL.center.x - self.bounds.size.width * .5;
    if (offset < 0) {
        offset = 0;
    }
    CGFloat maxOffset = self.scrollView.contentSize.width - self.bounds.size.width;
    if (offset > maxOffset) {
        offset = maxOffset;
    }
    
    [self.scrollView setContentOffset:CGPointMake(offset, 0) animated:YES];
}

- (void)setLabelFrames{
    CGFloat x = 0;
    CGFloat y = 0;
    CGFloat w = 0;
    CGFloat h = self.style.isShowScrollLine ? self.frame.size.height - self.style.scrollLineH : self.frame.size.height;
    for (int i = 0; i < self.titles.count; i++) {
        UILabel *label = self.labels[i];
        if (self.style.isScrollEnanble) {
            label.frame = CGRectMake(0, 0, 1, h);
            [label sizeToFit];
            w = label.frame.size.width;
            
            if (i == 0) {
                x = self.style.itemMargin * .5;
            }else{
                UILabel *previousLabel = self.labels[i - 1];
                x = CGRectGetMaxX(previousLabel.frame) + self.style.itemMargin;
            }
        }else{
            w = self.bounds.size.width / self.titles.count;
            x = w * i;
        }
        label.frame = CGRectMake(x, y, w, h);
        if (i == 0 && self.style.isNeedScale) {
            label.transform = CGAffineTransformMakeScale(self.style.scaleRaange, self.style.scaleRaange);
        }
        if (i != self.titles.count - 1 && self.style.isSpacingLin) {
            UIView *spacing = [[UIView alloc]init];
            spacing.frame = CGRectMake(CGRectGetMaxX(label.frame) + (self.style.itemMargin * .5 - .25), 5, .5, label.frame.size.height - 10);
            spacing.backgroundColor = self.style.spacingColor;
            [self.scrollView addSubview:spacing];
        }
    }
    
    if (self.style.isScrollEnanble) {
        UILabel *previousLabel = [self.labels lastObject];
        self.scrollView.contentSize = CGSizeMake(CGRectGetMaxX(previousLabel.frame) + self.style.itemMargin * .5, 0);
    }
    
    [self.scrollView addSubview:self.bottomLine];
    
    
}

#pragma mark - PublicMethod
- (void)setTitleWithProgress:(CGFloat)progress oldIndex:(NSInteger)index newIndex:(NSInteger)newIndex{
    
    UILabel *oldLabel = self.labels[index];
    UILabel *newLabel = self.labels[newIndex];
    NSArray *deltaRGB = [UIColor getColorDifferenceWith:self.style.selectColor secondColor:self.style.normalColor];
    NSArray *seleteColor = [self.style.selectColor getRGB];
    NSArray *normalColor = [self.style.normalColor getRGB];
    
    oldLabel.textColor = [UIColor colorWithRed:[seleteColor[0]floatValue] - [deltaRGB[0]floatValue] * progress green:[seleteColor[1]floatValue] - [deltaRGB[1]floatValue] * progress blue:[seleteColor[2]floatValue] - [deltaRGB[2]floatValue] * progress alpha:1];
    
    newLabel.textColor = [UIColor colorWithRed:[normalColor[0]floatValue] + [deltaRGB[0]floatValue] * progress green:[normalColor[1]floatValue] + [deltaRGB[1]floatValue] * progress blue:[normalColor[2]floatValue] + [deltaRGB[2]floatValue] * progress alpha:1];
    
    
    CGFloat deltaX = newLabel.frame.origin.x - oldLabel.frame.origin.x;
    CGFloat deltaW = newLabel.frame.size.width - oldLabel.frame.size.width;
    
    self.bottomLine.frame = CGRectMake(oldLabel.frame.origin.x + deltaX * progress, self.bottomLine.frame.origin.y, oldLabel.frame.size.width + deltaW * progress, self.bottomLine.frame.size.height);
    self.currentIndex = newIndex;
    
    
}

- (UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]init];
        if (self.style.popover) {
            _scrollView.frame = CGRectMake(0, 0, self.bounds.size.width - 50, self.bounds.size.height);
        }else{
            _scrollView.frame = self.bounds;
        }
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.scrollsToTop = NO;
    }
    return _scrollView;
}

- (UILabel *)bottomLine{
    if (!_bottomLine) {
        _bottomLine = [[UILabel alloc]init];
        UILabel *previousLabel = [self.labels firstObject];
        _bottomLine.frame = CGRectMake(CGRectGetMinX(previousLabel.frame), self.bounds.size.height - self.style.scrollLineH, previousLabel.frame.size.width, self.style.scrollLineH);
        _bottomLine.backgroundColor = self.style.scrollLineColor;
    }
    return _bottomLine;
}

- (NSMutableArray *)labels{
    if (!_labels) {
        _labels = [NSMutableArray array];
    }
    return _labels;
}

- (void)dealloc{
    NSLog(@"DockTitleView");
}
@end
